package cn.hfatec.web;

import cn.hfatec.constants.SysContant;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: panwb
 *
 * Date: 2015/2/27
 * Time: 11:12
 */
public class AbsolutelyPathInterceptor extends HandlerInterceptorAdapter {

    public static String getAbsolutePath(HttpServletRequest request) {
        String absoluteContextPath;
        if (request.getServerPort() == 80) {
            absoluteContextPath = request.getScheme() + "://" + request.getServerName() + request.getContextPath();
        } else if (request.getServerPort() == 443) {
            absoluteContextPath = request.getScheme() + "://" + request.getServerName() + request.getContextPath();
        } else {
            absoluteContextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        }
        return absoluteContextPath;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute(SysContant.ABSOLUTE_CONTEXT_PATH, getAbsolutePath(request));
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}
